<template>
  <div>
    <el-row>
      <el-col :span="24">
        <crmfilequickuploader
          :directory-name="'B2BOrderFiles'"
          @insert="handleInsertFile"
        />
      </el-col>
    </el-row>

    <!-- 精简工具栏 -->
    <el-row class="compact-toolbar" :gutter="10">
      <el-col :span="14">
        <el-select
          v-model="selectedFolder"
          placeholder="文件夹"
          size="mini"
          clearable
          style="width: 140px;"
          @change="handleFolderChange"
        >
          <el-option label="全部" value="" />
          <el-option
            v-for="folder in folders"
            :key="folder.name"
            :label="`${folder.name} (${getVisibleFolderCount(folder.name)})`"
            :value="folder.name"
          />
        </el-select>
        <el-button-group style="margin-left: 8px;">
          <el-button type="primary" size="mini" icon="el-icon-refresh" @click="refreshFolders" />
          <el-button type="success" size="mini" icon="el-icon-folder-add" @click="showCreateFolderDialog" />
        </el-button-group>
      </el-col>
      <el-col :span="10" class="text-right">
        <el-input
          v-model="kwInput"
          placeholder="搜索..."
          size="mini"
          style="width: 150px;"
          @keyup.enter="getList"
        >
          <el-button slot="append" icon="el-icon-search" size="mini" @click="getList" />
        </el-input>
      </el-col>
    </el-row>

    <!-- 文件夹视图 -->
    <div v-if="viewMode === 'folder'" v-loading="listLoading" class="folders-container">
      <div
        v-for="folder in foldersData"
        :key="folder.folder_name"
        class="folder-section"
        :class="{ 'drag-over': dragOverFolder === folder.folder_name }"
        @dragover.prevent="handleDragOver(folder.folder_name)"
        @dragleave="handleDragLeave"
        @drop="handleDrop(folder.folder_name)"
      >
        <div class="folder-header">
          <el-tag
            :type="getFolderTagType(folder.folder_name)"
            size="medium"
            class="folder-tag"
          >
            <i class="el-icon-folder" /> {{ folder.folder_name }} ({{ getVisibleFileCount(folder) }})
          </el-tag>
          <div v-if="dragOverFolder === folder.folder_name" class="drop-hint">
            <i class="el-icon-upload" /> 放到此文件夹
          </div>
        </div>
        <el-row :gutter="8" class="folder-content">
          <el-col v-for="item in filterPlaceholderFiles(folder.attachments)" :key="item.id" :span="4" class="mb-8">
            <div
              class="compact-file-card"
              :class="{ 'dragging': draggedItem && draggedItem.id === item.id }"
              draggable="true"
              @dragstart="handleDragStart(item, $event)"
              @dragend="handleDragEnd"
              @click="handleCardClick(item.crmfiles[0], $event)"
            >
              <div class="file-icon-container">
                <!-- 图片预览 -->
                <div
                  v-if="item.crmfiles[0] && item.crmfiles[0].content_type && item.crmfiles[0].content_type.indexOf('image') !== -1"
                  class="image-preview-container"
                  @mouseenter="showHoverPreview(item.crmfiles[0].url, $event)"
                  @mouseleave="hideHoverPreview"
                  @click.stop="previewImage(item.crmfiles[0].url)"
                >
                  <el-image
                    :src="item.crmfiles[0].url"
                    fit="cover"
                    class="small-file-icon"
                  />
                </div>
                <!-- 视频图标 -->
                <svg-icon
                  v-else-if="item.crmfiles[0] && hasExtension(item.crmfiles[0].filename, ['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm'])"
                  icon-class="video"
                  class="small-file-icon"
                />
                <!-- 文件图标 -->
                <template v-else-if="item.crmfiles[0]">
                  <svg-icon
                    v-if="hasExtension(item.crmfiles[0].filename, ['pdf'])"
                    icon-class="pdf"
                    class="small-file-icon"
                  />
                  <svg-icon
                    v-else-if="hasExtension(item.crmfiles[0].filename, ['xlsx', 'xls'])"
                    icon-class="excel"
                    class="small-file-icon"
                  />
                  <svg-icon
                    v-else-if="hasExtension(item.crmfiles[0].filename, ['doc', 'docx'])"
                    icon-class="word"
                    class="small-file-icon"
                  />
                  <svg-icon
                    v-else-if="hasExtension(item.crmfiles[0].filename, ['zip', 'rar', '7z'])"
                    icon-class="zip"
                    class="small-file-icon"
                  />
                  <svg-icon
                    v-else-if="hasExtension(item.crmfiles[0].filename, ['txt'])"
                    icon-class="txt"
                    class="small-file-icon"
                  />
                  <svg-icon
                    v-else
                    icon-class="document"
                    class="small-file-icon"
                  />
                </template>
              </div>
              <el-tooltip :content="item.crmfiles[0] ? item.crmfiles[0].filename : '未知文件'" placement="top">
                <div class="compact-file-name">{{ item.crmfiles[0] ? item.crmfiles[0].filename : '未知文件' }}</div>
              </el-tooltip>
              <div class="compact-file-actions">
                <el-dropdown trigger="click" size="mini" @click.stop>
                  <i class="el-icon-more action-icon" />
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="downloadFile(item.crmfiles[0])">
                      <i class="el-icon-download" /> 下载
                    </el-dropdown-item>
                    <el-dropdown-item @click.native="editAttachment(item)">
                      <i class="el-icon-edit" /> 编辑
                    </el-dropdown-item>
                    <el-dropdown-item @click.native="moveToFolder(item)">
                      <i class="el-icon-folder" /> 移动
                    </el-dropdown-item>
                    <el-dropdown-item divided @click.native="handleDelete(item)">
                      <i class="el-icon-delete" style="color: #F56C6C;" /> 删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 列表视图 -->
    <div v-else v-loading="listLoading" class="files-container">
      <el-row :gutter="8">
        <el-col v-for="item in data" :key="item.id" :span="4" class="mb-8">
          <div
            class="compact-file-card"
            :class="{ 'dragging': draggedItem && draggedItem.id === item.id }"
            draggable="true"
            @dragstart="handleDragStart(item, $event)"
            @dragend="handleDragEnd"
            @click="handleCardClick(item.crmfiles[0], $event)"
          >
            <div class="file-icon-container">
              <!-- 图片预览 -->
              <div
                v-if="item.crmfiles[0] && item.crmfiles[0].content_type && item.crmfiles[0].content_type.indexOf('image') !== -1"
                class="image-preview-container"
                @mouseenter="showHoverPreview(item.crmfiles[0].url, $event)"
                @mouseleave="hideHoverPreview"
                @click.stop="previewImage(item.crmfiles[0].url)"
              >
                <el-image
                  :src="item.crmfiles[0].url"
                  fit="cover"
                  class="small-file-icon"
                />
              </div>
              <!-- 视频图标 -->
              <svg-icon
                v-else-if="item.crmfiles[0] && hasExtension(item.crmfiles[0].filename, ['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm'])"
                icon-class="video"
                class="small-file-icon"
              />
              <!-- 文件图标 -->
              <template v-else-if="item.crmfiles[0]">
                <svg-icon
                  v-if="hasExtension(item.crmfiles[0].filename, ['pdf'])"
                  icon-class="pdf"
                  class="small-file-icon"
                />
                <svg-icon
                  v-else-if="hasExtension(item.crmfiles[0].filename, ['xlsx', 'xls'])"
                  icon-class="excel"
                  class="small-file-icon"
                />
                <svg-icon
                  v-else-if="hasExtension(item.crmfiles[0].filename, ['doc', 'docx'])"
                  icon-class="word"
                  class="small-file-icon"
                />
                <svg-icon
                  v-else-if="hasExtension(item.crmfiles[0].filename, ['zip', 'rar', '7z'])"
                  icon-class="zip"
                  class="small-file-icon"
                />
                <svg-icon
                  v-else-if="hasExtension(item.crmfiles[0].filename, ['txt'])"
                  icon-class="txt"
                  class="small-file-icon"
                />
                <svg-icon
                  v-else
                  icon-class="document"
                  class="small-file-icon"
                />
              </template>
            </div>
            <el-tooltip :content="item.crmfiles[0] ? item.crmfiles[0].filename : '未知文件'" placement="top">
              <div class="compact-file-name">{{ item.crmfiles[0] ? item.crmfiles[0].filename : '未知文件' }}</div>
            </el-tooltip>
            <div class="compact-file-actions">
              <el-dropdown trigger="click" size="mini" @click.stop>
                <i class="el-icon-more action-icon" />
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native="downloadFile(item.crmfiles[0])">
                    <i class="el-icon-download" /> 下载
                  </el-dropdown-item>
                  <el-dropdown-item @click.native="editAttachment(item)">
                    <i class="el-icon-edit" /> 编辑
                  </el-dropdown-item>
                  <el-dropdown-item @click.native="moveToFolder(item)">
                    <i class="el-icon-folder" /> 移动
                  </el-dropdown-item>
                  <el-dropdown-item divided @click.native="handleDelete(item)">
                    <i class="el-icon-delete" style="color: #F56C6C;" /> 删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 移动文件夹对话框 -->
    <el-dialog title="移动到文件夹" :visible.sync="moveDialogVisible" append-to-body width="400px">
      <el-form>
        <el-form-item label="目标文件夹">
          <el-select v-model="targetFolder" placeholder="选择文件夹">
            <el-option label="默认" value="默认" />
            <el-option
              v-for="folder in folders.filter(f => f.name !== '默认')"
              :key="folder.name"
              :label="folder.name"
              :value="folder.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="新建文件夹">
          <el-input v-model="newFolderName" placeholder="输入新文件夹名称" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="moveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmMove">确定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑附件对话框 -->
    <el-dialog title="编辑附件" :visible.sync="editDialogVisible" append-to-body width="500px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="文件夹">
          <el-select v-model="editForm.folder_tag" placeholder="选择文件夹">
            <el-option label="默认" value="默认" />
            <el-option
              v-for="folder in folders.filter(f => f.name !== '默认')"
              :key="folder.name"
              :label="folder.name"
              :value="folder.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="3"
            placeholder="输入文件描述"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEdit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 创建文件夹对话框 -->
    <el-dialog title="新建文件夹" :visible.sync="createFolderDialogVisible" append-to-body width="400px">
      <el-form ref="createFolderForm" :model="createFolderForm" :rules="createFolderRules" label-width="80px">
        <el-form-item label="文件夹名" prop="folderName">
          <el-input
            v-model="createFolderForm.folderName"
            placeholder="请输入文件夹名称"
            maxlength="50"
            show-word-limit
            @keyup.enter.native="confirmCreateFolder"
          />
          <div class="form-tip">
            <small class="text-muted">文件夹名不能与现有文件夹重复</small>
          </div>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="createFolderForm.description"
            type="textarea"
            :rows="2"
            placeholder="请输入文件夹描述（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="createFolderDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="createFolderLoading" @click="confirmCreateFolder">创建</el-button>
      </div>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog
      :visible.sync="imagePreviewVisible"
      width="60%"
      center
      append-to-body
      :show-close="true"
    >
      <img
        :src="currentPreviewImage"
        style="width: 100%; height: auto; max-height: 70vh; object-fit: contain;"
        @click="imagePreviewVisible = false"
      >
    </el-dialog>

    <!-- Hover预览 -->
    <div
      v-if="hoverPreviewVisible"
      :style="hoverPreviewStyle"
      class="hover-preview"
    >
      <img
        :src="hoverPreviewImage"
        style="width: 600px; height: auto; max-height: 400px; object-fit: contain;"
      >
    </div>
  </div>
</template>

<script>
import {
  getOrderAttachments,
  createOrderAttachment,
  updateOrderAttachment,
  deleteOrderAttachment,
  getOrderAttachmentFolders,
  moveAttachmentsToFolder
} from '@/api/crm/crmorderattachment'
import Crmfilequickuploader from '../../../components/crmfilequickuploader'

export default {
  name: 'Crmorderattachments',
  components: { Crmfilequickuploader },
  props: ['order_data'],
  data() {
    return {
      listLoading: false,
      data: [],
      foldersData: [],
      folders: [],
      selectedFolder: '',
      kwInput: '',
      viewMode: 'folder', // 'folder' | 'list'
      pagesize: 100,
      page: 1,
      total: 0,
      // 移动文件夹相关
      moveDialogVisible: false,
      targetFolder: '',
      newFolderName: '',
      currentAttachment: null,
      // 编辑相关
      editDialogVisible: false,
      editForm: {
        folder_tag: '',
        description: ''
      },
      // 创建文件夹相关
      createFolderDialogVisible: false,
      createFolderLoading: false,
      createFolderForm: {
        folderName: '',
        description: ''
      },
      createFolderRules: {
        folderName: [
          { required: true, message: '请输入文件夹名称', trigger: 'blur' },
          { min: 1, max: 50, message: '文件夹名称长度在 1 到 50 个字符', trigger: 'blur' },
          { validator: this.validateFolderName, trigger: 'blur' }
        ]
      },
      // 拖拽相关
      draggedItem: null,
      dragOverFolder: null,
      isDragging: false,
      // 图片预览相关
      imagePreviewVisible: false,
      currentPreviewImage: '',
      // hover预览相关
      hoverPreviewVisible: false,
      hoverPreviewImage: '',
      hoverPreviewStyle: {}
    }
  },
  watch: {
    order_data: {
      handler(v) {
        if (v && v.id) {
          this.getFolders()
          this.getList()
        }
      },
      immediate: true,
      deep: true
    },
    // 额外监听 order_data.id 的变化，确保订单切换时能够刷新
    'order_data.id': {
      handler(newId, oldId) {
        if (newId && newId !== oldId) {
          // 清空当前数据，避免显示旧数据
          this.data = []
          this.foldersData = []
          this.selectedFolder = ''
          // 重新获取新订单的附件
          this.getFolders()
          this.getList()
        }
      }
    }
  },
  methods: {
    // 检查文件扩展名的辅助方法
    hasExtension(filename, extensions) {
      if (!filename) return false
      const ext = filename.split('.').pop().toLowerCase()
      return extensions.includes(ext)
    },

    // 过滤占位符文件
    filterPlaceholderFiles(attachments) {
      if (!attachments) return []
      return attachments.filter(item => {
        // 检查文件名是否为占位符
        if (item.crmfiles && item.crmfiles[0] && item.crmfiles[0].filename) {
          return !item.crmfiles[0].filename.startsWith('_folder_placeholder_')
        }
        // 检查描述中是否包含占位符标识
        if (item.description && item.description.includes('文件夹占位符')) {
          return false
        }
        return true
      })
    },

    // 获取可见文件数量（排除占位符文件）
    getVisibleFileCount(folder) {
      if (!folder.attachments) return 0
      return this.filterPlaceholderFiles(folder.attachments).length
    },

    // 获取文件夹可见文件数量（用于下拉框显示）
    getVisibleFolderCount(folderName) {
      const folderData = this.foldersData.find(f => f.folder_name === folderName)
      if (!folderData) return 0
      return this.getVisibleFileCount(folderData)
    },

    // 获取文件夹标签类型（用于不同颜色区分）
    getFolderTagType(folderName) {
      // 为不同文件夹分配不同的颜色类型
      const colorMap = {
        '默认': 'primary',
        '图片': 'success',
        '文档': 'warning',
        '视频': 'danger',
        '音频': 'info'
      }

      // 如果有预定义的颜色，使用预定义颜色
      if (colorMap[folderName]) {
        return colorMap[folderName]
      }

      // 根据文件夹名称的哈希值分配颜色
      const hash = this.stringHash(folderName)
      const colorTypes = ['primary', 'success', 'warning', 'danger', 'info']
      return colorTypes[Math.abs(hash) % colorTypes.length]
    },

    // 字符串哈希函数
    stringHash(str) {
      let hash = 0
      if (str.length === 0) return hash
      for (let i = 0; i < str.length; i++) {
        const char = str.charCodeAt(i)
        hash = ((hash << 5) - hash) + char
        hash = hash & hash // 转换为32位整数
      }
      return hash
    },

    // 获取文件夹列表
    async getFolders() {
      try {
        const response = await getOrderAttachmentFolders({
          order_id: this.order_data.id
        })
        this.folders = response.data || []
      } catch (error) {
        console.error('获取文件夹失败:', error)
        this.folders = []
      }
    },

    // 刷新文件夹
    async refreshFolders() {
      await this.getFolders()
      this.getList()
    },

    // 文件夹选择改变
    handleFolderChange() {
      this.getList()
    },

    // 获取附件列表
    async getList() {
      this.listLoading = true
      try {
        const params = {
          order_id: this.order_data.id,
          kw: this.kwInput,
          pagesize: this.pagesize,
          page: this.page
        }

        if (this.selectedFolder) {
          // 按指定文件夹获取
          params.folder_tag = this.selectedFolder
          params.organize_by_folder = false
          this.viewMode = 'list'
        } else {
          // 按文件夹组织获取
          params.organize_by_folder = true
          this.viewMode = 'folder'
        }

        const response = await getOrderAttachments(params)

        if (response.data.organized_by_folder) {
          this.foldersData = response.data.folders || []
          this.data = []
        } else {
          this.data = response.data.data || []
          this.foldersData = []
        }

        this.total = response.data.total || 0
      } catch (error) {
        console.error('获取附件列表失败:', error)
        this.$message.error('获取附件列表失败')
      } finally {
        this.listLoading = false
      }
    },

    // 删除附件
    handleDelete(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await deleteOrderAttachment(row.id)

          // 直接更新本地数据
          this.removeItemFromLocalData(row)

          this.$message.success('删除成功!')
        } catch (error) {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 从本地数据中移除项目
    removeItemFromLocalData(item) {
      const folderName = item.folder_tag || '默认'

      // 从foldersData中移除
      const folderData = this.foldersData.find(f => f.folder_name === folderName)
      if (folderData) {
        const itemIndex = folderData.attachments.findIndex(att => att.id === item.id)
        if (itemIndex > -1) {
          folderData.attachments.splice(itemIndex, 1)
          folderData.count = folderData.attachments.length
        }
      }

      // 从列表数据中移除
      const listIndex = this.data.findIndex(att => att.id === item.id)
      if (listIndex > -1) {
        this.data.splice(listIndex, 1)
      }

      // 更新文件夹计数
      this.updateFolderCounts()

      // 强制更新视图
      this.$forceUpdate()
    },

    // 编辑附件
    editAttachment(item) {
      this.currentAttachment = item
      this.editForm = {
        folder_tag: item.folder_tag || '默认',
        description: item.description || ''
      }
      this.editDialogVisible = true
    },

    // 确认编辑
    async confirmEdit() {
      try {
        await updateOrderAttachment(this.currentAttachment.id, this.editForm)

        // 如果文件夹发生变化，需要移动文件
        const oldFolder = this.currentAttachment.folder_tag || '默认'
        const newFolder = this.editForm.folder_tag || '默认'

        if (oldFolder !== newFolder) {
          // 更新本地数据中的文件夹
          this.updateLocalDataAfterDrop(this.currentAttachment, oldFolder, newFolder)
        }

        // 更新本地数据中的描述
        this.currentAttachment.description = this.editForm.description
        this.currentAttachment.folder_tag = this.editForm.folder_tag

        this.editDialogVisible = false
        this.$message.success('更新成功')

        // 强制更新视图
        this.$forceUpdate()
      } catch (error) {
        console.error('更新失败:', error)
        this.$message.error('更新失败')
      }
    },

    // 移动到文件夹
    moveToFolder(item) {
      this.currentAttachment = item
      this.targetFolder = item.folder_tag || '默认'
      this.newFolderName = ''
      this.moveDialogVisible = true
    },

    // 确认移动
    async confirmMove() {
      try {
        const folderName = this.newFolderName.trim() || this.targetFolder
        if (!folderName) {
          this.$message.warning('请选择或输入文件夹名称')
          return
        }

        const oldFolder = this.currentAttachment.folder_tag || '默认'

        await moveAttachmentsToFolder({
          attachment_ids: [this.currentAttachment.id],
          target_folder: folderName
        })

        // 直接更新本地数据
        this.updateLocalDataAfterDrop(this.currentAttachment, oldFolder, folderName)

        this.moveDialogVisible = false
        this.$message.success(`已移动到文件夹 "${folderName}"`)
      } catch (error) {
        console.error('移动失败:', error)
        this.$message.error('移动失败')
      }
    },

    // 显示创建文件夹对话框
    showCreateFolderDialog() {
      this.createFolderForm = {
        folderName: '',
        description: ''
      }
      this.createFolderDialogVisible = true
      this.$nextTick(() => {
        this.$refs.createFolderForm.clearValidate()
      })
    },

    // 验证文件夹名称是否重复
    validateFolderName(rule, value, callback) {
      if (!value) {
        callback()
        return
      }

      const trimmedValue = value.trim()
      if (trimmedValue === '默认') {
        callback(new Error('文件夹名称不能为"默认"'))
        return
      }

      // 检查是否与现有文件夹重复
      const existingFolder = this.folders.find(folder =>
        folder.name.toLowerCase() === trimmedValue.toLowerCase()
      )

      if (existingFolder) {
        callback(new Error('该文件夹名称已存在'))
        return
      }

      callback()
    },

    // 确认创建文件夹
    async confirmCreateFolder() {
      try {
        // 验证表单
        await this.$refs.createFolderForm.validate()

        this.createFolderLoading = true
        const folderName = this.createFolderForm.folderName.trim()

        // 创建一个虚拟附件来"创建"文件夹
        // 由于后端没有专门的创建文件夹接口，我们通过创建一个临时附件来实现
        await createOrderAttachment({
          order_id: this.order_data.id,
          filename: `_folder_placeholder_${Date.now()}.txt`,
          file_url: '',
          description: `文件夹占位符: ${this.createFolderForm.description || ''}`,
          folder_tag: folderName,
          crmfiles: []
        })

        this.createFolderDialogVisible = false
        this.createFolderLoading = false

        // 刷新文件夹列表和附件列表
        await this.getFolders()
        this.getList()

        // 自动选择新创建的文件夹
        this.selectedFolder = folderName

        this.$message.success(`文件夹 "${folderName}" 创建成功`)
      } catch (error) {
        this.createFolderLoading = false
        if (error.message && error.message !== 'error') {
          // 表单验证错误
          return
        }
        console.error('创建文件夹失败:', error)
        this.$message.error('创建文件夹失败')
      }
    },

    // 拖拽相关方法
    handleDragStart(item, event) {
      this.draggedItem = item
      this.isDragging = true

      // 设置拖拽数据
      event.dataTransfer.setData('text/plain', JSON.stringify({
        id: item.id,
        filename: item.crmfiles[0] ? item.crmfiles[0].filename : '未知文件',
        currentFolder: item.folder_tag || '默认'
      }))

      event.dataTransfer.effectAllowed = 'move'

      // 设置拖拽图像
      const dragImage = event.target.cloneNode(true)
      dragImage.style.opacity = '0.8'
      dragImage.style.transform = 'rotate(5deg)'
      document.body.appendChild(dragImage)
      event.dataTransfer.setDragImage(dragImage, 35, 35)

      setTimeout(() => {
        document.body.removeChild(dragImage)
      }, 0)
    },

    handleDragEnd() {
      this.draggedItem = null
      this.isDragging = false
      this.dragOverFolder = null
    },

    handleDragOver(folderName) {
      if (!this.isDragging || !this.draggedItem) return

      const currentFolder = this.draggedItem.folder_tag || '默认'
      if (currentFolder !== folderName) {
        this.dragOverFolder = folderName
      }
    },

    handleDragLeave() {
      this.dragOverFolder = null
    },

    async handleDrop(targetFolder) {
      if (!this.draggedItem) return

      this.dragOverFolder = null
      const currentFolder = this.draggedItem.folder_tag || '默认'

      // 如果是同一个文件夹，则不做任何操作
      if (currentFolder === targetFolder) {
        this.draggedItem = null
        this.isDragging = false
        return
      }

      // 保存拖拽的文件信息，避免在清空后无法访问
      const draggedItemInfo = {
        id: this.draggedItem.id,
        fileName: this.draggedItem.crmfiles && this.draggedItem.crmfiles[0]
          ? this.draggedItem.crmfiles[0].filename
          : '未知文件',
        fullItem: { ...this.draggedItem }
      }

      try {
        // 移动文件到目标文件夹
        await moveAttachmentsToFolder({
          attachment_ids: [draggedItemInfo.id],
          target_folder: targetFolder
        })

        // 直接更新本地数据，避免重新请求API
        this.updateLocalDataAfterDrop(draggedItemInfo.fullItem, currentFolder, targetFolder)

        this.$message.success(`已将 "${draggedItemInfo.fileName}" 移动到文件夹 "${targetFolder}"`)
      } catch (error) {
        console.error('拖拽移动失败:', error)
        this.$message.error('移动文件失败')
      } finally {
        this.draggedItem = null
        this.isDragging = false
      }
    },

    // 更新本地数据，避免重新请求API
    updateLocalDataAfterDrop(draggedItem, sourceFolder, targetFolder) {
      // 更新被拖拽项目的folder_tag
      draggedItem.folder_tag = targetFolder

      // 从源文件夹中移除该项目
      const sourceFolderData = this.foldersData.find(f => f.folder_name === sourceFolder)
      if (sourceFolderData) {
        const itemIndex = sourceFolderData.attachments.findIndex(item => item.id === draggedItem.id)
        if (itemIndex > -1) {
          sourceFolderData.attachments.splice(itemIndex, 1)
          sourceFolderData.count = sourceFolderData.attachments.length
        }
      }

      // 添加到目标文件夹
      let targetFolderData = this.foldersData.find(f => f.folder_name === targetFolder)
      if (!targetFolderData) {
        // 如果目标文件夹不存在，创建一个新的文件夹数据
        targetFolderData = {
          folder_name: targetFolder,
          count: 0,
          attachments: []
        }
        this.foldersData.push(targetFolderData)
      }

      // 将项目添加到目标文件夹
      targetFolderData.attachments.push(draggedItem)
      targetFolderData.count = targetFolderData.attachments.length

      // 更新文件夹计数信息
      this.updateFolderCounts()

      // 强制触发视图更新
      this.$forceUpdate()
    },

    // 更新文件夹计数
    updateFolderCounts() {
      this.folders.forEach(folder => {
        const folderData = this.foldersData.find(f => f.folder_name === folder.name)
        if (folderData) {
          folder.count = folderData.count
        }
      })
    },

    // 处理卡片点击事件
    handleCardClick(file, event) {
      // 如果点击的是图片，不执行下载（图片有单独的预览点击事件）
      if (file && file.content_type && file.content_type.indexOf('image') !== -1) {
        return
      }

      // 非图片文件执行下载
      this.downloadFile(file)
    },

    // 预览图片
    previewImage(imageUrl) {
      this.currentPreviewImage = imageUrl
      this.imagePreviewVisible = true
    },

    // 显示hover预览
    showHoverPreview(imageUrl, event) {
      this.hoverPreviewImage = imageUrl
      this.hoverPreviewVisible = true

      // 计算预览框位置
      const rect = event.target.getBoundingClientRect()

      this.hoverPreviewStyle = {
        position: 'fixed',
        left: rect.right + 10 + 'px',
        top: rect.top + 'px',
        zIndex: 9999
      }

      // 如果右侧空间不够，显示在左侧
      if (rect.right + 610 > window.innerWidth) {
        this.hoverPreviewStyle.left = rect.left - 610 + 'px'
      }

      // 如果下方空间不够，向上调整
      if (rect.top + 400 > window.innerHeight) {
        this.hoverPreviewStyle.top = window.innerHeight - 400 + 'px'
      }
    },

    // 隐藏hover预览
    hideHoverPreview() {
      this.hoverPreviewVisible = false
    },

    downloadFile(item) {
      if (!item || !item.url) return

      const link = document.createElement('a')
      link.href = item.url
      link.download = item.filename || '下载文件'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },

    // 插入文件
    async handleInsertFile(item) {
      try {
        const response = await createOrderAttachment({
          order_id: this.order_data.id,
          filename: item.filename,
          file_url: item.url,
          description: JSON.stringify(item, null, 2),
          folder_tag: item.folder_tag || '默认', // 使用文件的folder_tag，如果没有则默认为'默认'
          crmfiles: [item.id]
        })

        // 直接更新本地数据
        this.addItemToLocalData(response.data, item, item.folder_tag || '默认')

        this.$message.success('添加成功')
      } catch (error) {
        console.error('添加失败:', error)
        this.$message.error('添加失败')
      }
    },

    // 添加项目到本地数据
    addItemToLocalData(newAttachment, fileItem, folderTag = '默认') {
      // 构造新的附件对象
      const newItem = {
        ...newAttachment,
        crmfiles: [fileItem]
      }

      // 添加到指定文件夹
      let targetFolderData = this.foldersData.find(f => f.folder_name === folderTag)
      if (!targetFolderData) {
        targetFolderData = {
          folder_name: folderTag,
          count: 0,
          attachments: []
        }
        // 如果是默认文件夹，排在前面；否则添加到后面
        if (folderTag === '默认') {
          this.foldersData.unshift(targetFolderData)
        } else {
          this.foldersData.push(targetFolderData)
        }
      }

      // 添加到文件夹数据
      targetFolderData.attachments.push(newItem)
      targetFolderData.count = targetFolderData.attachments.length

      // 更新文件夹计数
      const targetFolder = this.folders.find(f => f.name === folderTag)
      if (targetFolder) {
        targetFolder.count = targetFolderData.count
      } else {
        const newFolder = {
          name: folderTag,
          count: targetFolderData.count
        }
        // 如果是默认文件夹，排在前面；否则添加到后面
        if (folderTag === '默认') {
          this.folders.unshift(newFolder)
        } else {
          this.folders.push(newFolder)
        }
      }

      // 强制更新视图
      this.$forceUpdate()
    }
  }
}
</script>

<style scoped>
/* 精简工具栏样式 */
.compact-toolbar {
  margin: 10px 0;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.text-right {
  text-align: right;
}

/* 文件夹容器样式 */
.folders-container {
  margin-top: 12px;
}

.folder-section {
  margin-bottom: 16px;
}

.folder-header {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
  padding: 6px 0;
  border-bottom: 1px solid #e4e7ed;
}

.folder-content {
  margin-top: 8px;
}

.folder-tag {
  font-weight: 600;
  font-size: 13px;
  padding: 6px 12px !important;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.2s;
  height: auto !important;
  line-height: 1.4 !important;
  display: inline-flex !important;
  align-items: center !important;
  vertical-align: middle !important;
}

.folder-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.folder-tag .el-icon-folder {
  margin-right: 6px;
  font-size: 14px;
  line-height: 1;
}

/* 文件容器样式 */
.files-container {
  margin-top: 12px;
}

.mb-8 {
  margin-bottom: 8px;
}

/* 紧凑文件卡片样式 */
.compact-file-card {
  position: relative;
  padding: 6px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fff;
  cursor: pointer;
  transition: all 0.2s;
  height: 70px;
  display: flex;
  align-items: center;
}

.compact-file-card:hover {
  border-color: #409EFF;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.12);
  transform: translateY(-1px);
}

.file-icon-container {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  flex-shrink: 0;
}

.small-file-icon {
  width: 28px;
  height: 28px;
  border-radius: 2px;
}

.compact-file-name {
  flex: 1;
  font-size: 12px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.2;
  margin-right: 8px;
}

.compact-file-actions {
  position: absolute;
  top: 4px;
  right: 4px;
  opacity: 0;
  transition: opacity 0.2s;
}

.compact-file-card:hover .compact-file-actions {
  opacity: 1;
}

.action-icon {
  color: #909399;
  font-size: 14px;
  cursor: pointer;
  padding: 2px;
}

.action-icon:hover {
  color: #409EFF;
}

/* 拖拽样式 */
.compact-file-card.dragging {
  opacity: 0.5;
  transform: rotate(3deg);
  border-color: #409EFF;
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

.folder-section.drag-over {
  background: rgba(64, 158, 255, 0.1);
  border: 2px dashed #409EFF;
  border-radius: 6px;
  transition: all 0.2s;
}

.drop-hint {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #409EFF;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
  background: rgba(64, 158, 255, 0.1);
  padding: 2px 8px;
  border-radius: 4px;
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
}

/* 图片预览相关样式 */
.image-preview-container {
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.hover-preview {
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  padding: 8px;
  pointer-events: none;
}

/* 表单提示样式 */
.form-tip {
  margin-top: 5px;
}

.text-muted {
  color: #909399;
}

/* 响应式布局 */
@media screen and (max-width: 1400px) {
  .el-col {
    max-width: 20%;
    flex: 0 0 20%;
  }
}

@media screen and (max-width: 1200px) {
  .el-col {
    max-width: 16.66%;
    flex: 0 0 16.66%;
  }
}

@media screen and (max-width: 992px) {
  .el-col {
    max-width: 12.5%;
    flex: 0 0 12.5%;
  }
}

@media screen and (max-width: 768px) {
  .el-col {
    max-width: 25%;
    flex: 0 0 25%;
  }

  .compact-file-card {
    height: 60px;
  }

  .compact-file-name {
    font-size: 11px;
  }
}

@media screen and (max-width: 480px) {
  .el-col {
    max-width: 50%;
    flex: 0 0 50%;
  }

  .compact-file-card {
    height: 50px;
  }

  .file-icon-container {
    width: 24px;
    height: 24px;
    margin-right: 6px;
  }

  .small-file-icon {
    width: 20px;
    height: 20px;
  }

  .compact-file-name {
    font-size: 10px;
  }
}
</style>
